package com.limm.myapplication;

import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.util.Pair;
import android.view.Gravity;
import android.view.SurfaceHolder;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.SeekBar;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.limm.myapplication.databinding.ActivityVideoBinding;
import com.limm.myapplication.viewmodel.PlayerViewModel;
import com.limm.myapplication.vo.PlayStatus;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class VideoActivity extends AppCompatActivity {

    private ActivityVideoBinding binding;
    private PlayerViewModel playerViewModel;
    private final ExecutorService executorService = Executors.newSingleThreadExecutor();

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityVideoBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        Log.e("onCreate", "onCreate");
        listenerViewModel();
//        getLifecycle().addObserver(playerViewModel.mediaPlayer);
        elementListener();
        updatePlayerProgress();

    }

    private void elementListener() {
        binding.surfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(@NonNull SurfaceHolder holder) {

            }

            @Override
            public void surfaceChanged(@NonNull SurfaceHolder holder, int format, int width, int height) {
                playerViewModel.mediaPlayer.setDisplay(holder);
                playerViewModel.mediaPlayer.setScreenOnWhilePlaying(true);
            }

            @Override
            public void surfaceDestroyed(@NonNull SurfaceHolder holder) {

            }
        });
        binding.playerFrame.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                playerViewModel.toggleControllerVisibility();
            }
        });
        binding.controllerLayout.seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser) {
                    playerViewModel.playSeekToProgress(progress);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

        binding.controllerLayout.player.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                playerViewModel.togglePlayerStatus();
            }
        });
    }

    private void listenerViewModel() {
        playerViewModel = new ViewModelProvider(this,
                new ViewModelProvider.AndroidViewModelFactory(getApplication()))
                .get(PlayerViewModel.class);
        getLifecycle().addObserver(playerViewModel.mediaPlayer);

        playerViewModel = new ViewModelProvider(this,
                new ViewModelProvider.AndroidViewModelFactory(getApplication()))
                .get(PlayerViewModel.class);

        getLifecycle().addObserver(playerViewModel.mediaPlayer);
        playerViewModel.getProgressBarVisibility().observe(this, new Observer<Integer>() {
            @Override
            public void onChanged(Integer integer) {
                binding.progressBar.setVisibility(integer);
            }
        });

        playerViewModel.getVideoResolution().observe(this, new Observer<Pair<Integer, Integer>>() {
            @Override
            public void onChanged(Pair<Integer, Integer> pair) {
                binding.controllerLayout.seekBar.setMax(playerViewModel.mediaPlayer.getDuration());
                binding.playerFrame.post(new Runnable() {
                    @Override
                    public void run() {
                        resize(pair.first, pair.second);
                    }
                });
            }
        });
        playerViewModel.getControllerFrameVisibility().observe(this, new Observer<Integer>() {
            @Override
            public void onChanged(Integer integer) {
                binding.controllerLayout.controllerFrame.setVisibility(integer);
            }
        });

        playerViewModel.getBufferPercent().observe(this, new Observer<Integer>() {
            @Override
            public void onChanged(Integer it) {
                int progress = binding.controllerLayout.seekBar.getMax() * it / 100;
                binding.controllerLayout.seekBar.setSecondaryProgress(progress);

                binding.surfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {
                    @Override
                    public void surfaceCreated(@NonNull SurfaceHolder holder) {

                    }

                    @Override
                    public void surfaceChanged(@NonNull SurfaceHolder holder, int format, int width, int height) {
                        playerViewModel.mediaPlayer.setDisplay(holder);
                        playerViewModel.mediaPlayer.setScreenOnWhilePlaying(true);
                    }

                    @Override
                    public void surfaceDestroyed(@NonNull SurfaceHolder holder) {

                    }
                });
            }
        });

        playerViewModel.getPlayStatus().observe(this, new Observer<PlayStatus>() {
            @Override
            public void onChanged(PlayStatus playStatus) {
                listenerPlayStatus(playStatus);
            }
        });
    }

    private void listenerPlayStatus(PlayStatus playStatus) {
        binding.controllerLayout.player.setClickable(true);
        switch (playStatus) {
            case Paused: {
                binding.controllerLayout.player.setImageResource(R.drawable.ic_baseline_play_arrow_24);
                break;
            }
            case NoReady: {
                binding.controllerLayout.player.setClickable(false);
                break;
            }
            case Completed: {
                binding.controllerLayout.player.setImageResource(R.drawable.ic_baseline_replay_24);
                break;
            }
            default: {
                binding.controllerLayout.player.setImageResource(R.drawable.ic_baseline_pause_24);
                break;
            }
        }
    }


    private void resize(int w, int h) {
        if (w == 0 || h == 0) {
            return;
        }
        FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(
                binding.playerFrame.getHeight() * w / h, FrameLayout.LayoutParams.MATCH_PARENT, Gravity.CENTER);
        binding.surfaceView.setLayoutParams(layoutParams);
    }


    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    private void hideSystemUI() {
        this.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                | View.SYSTEM_UI_FLAG_FULLSCREEN
                | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
        );
    }

    private void updatePlayerProgress() {
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    binding.controllerLayout.seekBar.setProgress(playerViewModel.mediaPlayer.getCurrentPosition());
                }
            }
        });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (playerViewModel.executors.isShutdown()) {
            playerViewModel.executors.shutdown();
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            hideSystemUI();
            playerViewModel.emmitVideoResolution();
        }
    }

    @Override
    public void onConfigurationChanged(@NonNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
//        playerViewModel.mediaPlayer.stop();

    }

}
//    window.decorView.systemUiVisibility = (View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
//    // Set the content to appear under the system bars so that the
//    // content doesn't resize when the system bars hide and show.
//    or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
//    or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
//    or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
//    // Hide the nav bar and status bar
//    or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
//    or View.SYSTEM_UI_FLAG_FULLSCREEN)

